﻿using AutoMapper;
using B.S.BasicData.Api.Read.Application.Command.BaoBiao;
using B.S.BasicData.Api.Read.DTO;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Read.Application.Handler.BaoBiao
{
    public class GetZongBaoBiaoHandler : IRequestHandler<GetZongBaoBiaoCommand, ApiResult<List<BaoBiaoDTO>>>
    {
        private readonly IBaseRepository<UserModel> userRepo;
        private readonly IBaseRepository<ApprovalModel> approvalRepo;
        private readonly MyDbContext db;

        public GetZongBaoBiaoHandler(IBaseRepository<UserModel> userRepo,IBaseRepository<ApprovalModel> approvalRepo,MyDbContext db)
        {
            this.userRepo = userRepo;
            this.approvalRepo = approvalRepo;
            this.db = db;
        }
        public  Task<ApiResult<List<BaoBiaoDTO>>> Handle(GetZongBaoBiaoCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<BaoBiaoDTO>> res = new ApiResult<List<BaoBiaoDTO>>();
            var user = db.UserModels.ToList();
           
            var result=new List<BaoBiaoDTO>();
            foreach(var item in user)
            {
                var sumary = new BaoBiaoDTO()
                {
                    Uid = item.Id,
                    Uname = item.UserName,
                    Moths  = new List<int>(new int[12]).ToList(),
                };
                var approval = approvalRepo.GetAll().Where(x => x.Uid == item.Id && x.LeaveStatrTime.Year == request.Year).ToList();
                foreach (var items in approval)
                {
                    int mouth = items.LeaveStatrTime.Month - 1;
                    sumary.Moths[mouth] += items.CountHours;
                }
                result.Add(sumary);
            }
            res.Data = result;
            res.Code = ApiEnum.Success;
            res.Msg = "显示总时长成功";
            return Task.FromResult(res);
        }
    }
}
